<script setup lang="ts" name="EaTask">
import { Plus, Edit, Search, ArrowDown } from '@element-plus/icons-vue'
import type { EaTask } from './type'
import Detail from './Detail.vue'
import Form from './Form.vue'

import { checkPermission } from '@/utils/permission'

const baseApi = '/ea/ea-task-record'

const { queryParam, loading, dataList, pagination, getList, onSearch, resetFilter, remove, batchRemove } =
  useList<EaTask>({ baseApi, initQueryParam: {} })

defineExpose({
  refresh: onSearch,
  addCondition: (key: keyof EaTask, value: any, refresh = false) => {
    queryParam[key] = value
    if (refresh) onSearch()
  }
})

const { initRelatedData, relatedData } = useOption({
  load: {
    memberIdOptions: { type: 'IamMember', label: 'nickname' }
  }
})
initRelatedData()

const sortChange = ({ column, prop, order }: { column: { sortBy?: string }; prop: string; order: string }) => {
  let orderBy: 'ASC' | 'DESC' | undefined
  switch (order) {
    case 'ascending':
      orderBy = 'ASC'
      break
    case 'descending':
      orderBy = 'DESC'
      break
    default:
      orderBy = undefined
  }
  pagination.orderBy = orderBy ? `${column.sortBy ?? prop}:${orderBy}` : undefined
  onSearch()
}

const formRef = ref()
const formTitle = ref('')
const submitting = ref(false)
const formVisible = ref(false)
const addSustainably = ref<boolean>(false)

const openForm = (id?: string) => {
  if (id) {
    addSustainably.value = false
    formTitle.value = '编辑'
  } else {
    addSustainably.value = true
    formTitle.value = '新建'
  }
  formVisible.value = true

  nextTick(() => formRef.value?.init(id))
}

const closeForm = () => {
  formVisible.value = false
}

const submit = (goOn = false) => {
  formRef.value?.submit().then((result: boolean) => {
    if (result) {
      if (!goOn) {
        formVisible.value = false
      }
      formRef.value?.reset()
    }
  })
}

const detailRef = ref()
const detailVisible = ref(false)
const dataId = ref('')

const openDetail = (id: string) => {
  dataId.value = id
  detailVisible.value = true

  nextTick(() => detailRef.value?.init(id))
}

const closeDetail = () => {
  detailVisible.value = false
}
const closeDetailAndOpenForm = () => {
  detailVisible.value = false
  openForm(dataId.value)
}

const handleOperation = (code: string, value?: string | string[]) => {
  switch (code) {
    case 'detail':
      openDetail(value as string)
      break
    case 'create':
    case 'update':
      openForm(value as string)
      break
    case 'remove':
      remove(value as string)
      break
    case 'batchRemove':
      batchRemove(value as string[])
      break
    default:
      throw new Error(`不存在的操作编码${code}!`)
  }
}

const orderReceivingInfo = value => {
  router.push({
    path: '/ea/ea-task/order-receiving-info',
    query: {
      id: value
    }
  })
}

const sum = (prop: keyof EaTask, fractionDigits?: number) =>
  Number(
    (dataList ?? [])
      .map(e => Number(e[prop] ?? 0))
      .reduce((e1, e2) => e1 + e2, 0)
      .toFixed(fractionDigits)
  )

const ave = (prop: keyof EaTask, fractionDigits?: number) =>
  Number(
    ((dataList ?? []).map(e => Number(e[prop] ?? 0)).reduce((e1, e2) => e1 + e2, 0) / (dataList ?? []).length).toFixed(
      fractionDigits
    )
  )

const refreshData = (haveNewData?: boolean) => {
  haveNewData ? onSearch() : getList()
}

const router = useRouter()

const activated = () => {
  nextTick(() => {
    const query = router.currentRoute.value.query
    for (const queryKey in query) {
      queryParam[queryKey as keyof EaTask] = query[queryKey] as any
    }

    onSearch()
  })
}

router.currentRoute.value.meta.keepAlive ? onActivated(activated) : activated()
</script>

<template>
  <div class="list-page">
    <el-table
      ref="tableRef"
      v-loading="loading"
      class="list-body"
      :data="dataList"
      height="100%"
      stripe
      row-key="id"
      style="border-top: 1px solid var(--el-border-color-lighter)"
      @sort-change="sortChange"
    >
      <el-table-column label="工人" prop="workerIdLabel" show-overflow-tooltip />
      <el-table-column label="抢单时间" prop="rushTaskTime" show-overflow-tooltip width="200" />
      <el-table-column label="结单时间" prop="confirmTime" show-overflow-tooltip />
      <el-table-column label="开始时间" prop="workStartTime" show-overflow-tooltip />
      <el-table-column label="结束时间" prop="workEndTime" show-overflow-tooltip />
      <el-table-column label="完成时间" prop="completeTime" show-overflow-tooltip />
      <el-table-column label="完成图片" prop="completePic" show-overflow-tooltip>
        <template #default="{ row }: { row: IamMember }">
          <el-image :src="row.workerAvatarUrl" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="佣金" prop="rakeOff" show-overflow-tooltip />
      <el-table-column label="任务状态" prop="taskStatus" show-overflow-tooltip />
      <el-table-column label="确认时间" prop="verifyTime" show-overflow-tooltip />
      <el-table-column label="加价佣金" prop="raiseRakeOff" show-overflow-tooltip />
      <el-table-column label="总佣金" prop="totalRakeOff" show-overflow-tooltip />
      <el-table-column label="结算时间" prop="settlementTime" show-overflow-tooltip />
    </el-table>

    <el-pagination
      v-if="pagination.total"
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 15, 20, 30, 50, 100]"
      small
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="getList()"
      @current-change="getList()"
    />
  </div>
</template>

<style scoped lang="scss">
.option {
  display: flex;
  justify-content: space-between;

  .ext {
    font-size: var(--el-font-size-extra-small);
    color: var(--el-text-color-secondary);
  }
}
</style>
